<template>
	<view class="shopping-cart">
		<view class="page-bg-gray"></view>
		<block v-if="isLogin == false">
			<view class="empty">
				<u-empty text="请先登陆" mode="permission" iconSize="180" fontSize="36">
					<view slot="bottom">
						<button class="confirm-btn" @click="utils.myUrl.gotoLogin">
							登录
						</button>
					</view>
				</u-empty>
			</view>
		</block>
		<block v-else>
		<view class="empty" v-if="cartList.length < 1">
			<u-empty text="购物车空空的" mode="car" iconSize="180" fontSize="36"></u-empty>
		</view>
		<view class="cart-list">
			<view class="cart-group" v-for="(gg,ggi) in groupList" :key="ggi">
				<view class="cart-group-title">
					<view class="title-text">
						<u-icon name="car" :size="30" color="rgb(94,94,94)"></u-icon>
						<span class="text">{{ gg.activity_name }}</span>
						<u-icon name="arrow-right" :size="20" color="rgb(94,94,94)"></u-icon>
					</view>
					<view class="title-right">
						
					</view>
				</view>
				<view class="cart-group-title cart-group-remark" v-if="gg.type">
					<u-tag :text="gg.type" mode="plain" shape="circle" type="error" size="mini" />
					<text class="promotion-text">{{gg.remark}}</text>
				</view>
				<u-swipe-action v-for="(item, index) in cartList" :btnWidth="btnWidth" @open="swipeActionOpen"
				@click="swipeActionClick"
				:key="index" :index="index" :show="item.show" :options="options" v-if="listIsShow(gg.cart_ids,item.id)">
					<view class="cart-item">
						<view class="select-btn is-disable" v-if="item.is_disable">
							<text class="txt">失效</text>
						</view>
					<view class="select-btn" v-else @click.stop="selectBtnClick(item)">
						<u-checkbox shape="circle" :value="item.checked" :name="index"
						@change="checkboxChange"
						active-color="#d81e06"
						></u-checkbox>
					</view>
					<view class="goods-box">
						<view class="pictrue" @click="gotoGoodsDetails(item.goods_id)">
							<image class="img" :src="photoBaseUrl + item.goods_cover" mode=""></image>
						</view>
						<view class="info">
							<view class="goods-name" @click="gotoGoodsDetails(item.goods_id)">
								{{item.goods_name}}
							</view>
							<view class="specs">
								<view class="btn" @click="changeGoodsOption(item)" v-if="item.option_name!='默认'">
									规格：{{item.option_name}}
									<u-icon class="icon" name="arrow-down" :size="24" color="rgb(94,94,94)"></u-icon>
								</view>
								<view class="btn" v-else>
									
								</view>
								<view class="btn" @click="changePromotion(item,gg.activity_id)" v-if="isShowChangePromotion(item.id)">
									换促销
									<u-icon class="icon" name="arrow-down" :size="24" color="rgb(94,94,94)"></u-icon>
								</view>
							</view>
							<view class="money">
								<view class="text">
									￥ {{cartFormatPrice(item['price'])}}
								</view>
								<view class="btn">
									<u-number-box :value="item.total" :index="index"
									:min="item.buy_min" :max="item.buy_max" :step="item.buy_step"
									@change="uNumberBoxChange"
									:disabled="item.is_disable === 1"
									></u-number-box>
								</view>
							</view>
							<view class="money" v-if="item.checked">
								<view class="text">
									预估到手价 ￥ {{cartFormatPrice(item['practical_price'])}}
								</view>
							</view>
							<view class="goods-tips" v-if="item.old_sell_price > item.price">
								比加入购物车时优惠{{cartFormatPrice(item['old_sell_price'] - item['price'])}}元
							</view>
						</view>
					</view>
					</view>
				</u-swipe-action>
			</view>
		</view>
		<view class="cart-bar">
			<view class="select-btn" @click="selectAll">
				<u-checkbox shape="circle" active-color="#d81e06" v-model="isSelectAll"
				>全选</u-checkbox>
			</view>
			<view class="money">
				<view class="total">合计：￥{{ showPrice }}</view>
				<view class="discount" @click="showCouponDetails">
					优惠减：￥ {{ totalDiscountPrice }} 
					<u-icon custom-prefix="g-icon" name="shang" class="discount-up" size="16"></u-icon>
				</view>
			</view>
			<view class="btn">
				<view class="addSite" :class="(isDisabled) ? 'disabled':''"
				@click="submitCart">
					<view class="add">
						<u-loading mode="flower" :show="isLoading"></u-loading> 结算 ({{selectOrderCount}})
					</view>
				</view>
			</view>
		</view>
		</block>
		
		<u-popup mode="bottom" safe-area-inset-bottom v-model="couponDetails">
			<view class="detailsContent">
				<scroll-view scroll-y="true" style="height: 600rpx;">
					<view>
						<u-cell-group>
							<u-cell-item :arrow="false" title="商品总额">
								<view slot="right-icon" class="">
									￥ {{cartFormatPrice(totalGoodsMoney)}}
								</view>
							</u-cell-item>
							<u-cell-item :arrow="false" :title="item.type+':'+item.remark" v-for="(item,index) in groupList" 
							v-if="item.activity_id>0 && item.discount_price>0" :key="index">
								<view slot="right-icon" class="discount-price">
									- ￥ {{cartFormatPrice(item.discount_price)}}
								</view>
							</u-cell-item>
						</u-cell-group>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		
		<u-popup mode="bottom" safe-area-inset-bottom v-model="changePromotionPopupShow">
			<view class="promotion-popup-content">
				<view class="goods-box">
					<view class="info-left">
						<image class="goods-image" :src="promotionChangeGoods.cover" mode="widthFix"></image>
					</view>
					<view class="info-right">
						<view class="title">
							{{ promotionChangeGoods.goods_name }}
						</view>
						<view class="price">
							￥ {{ cartFormatPrice(promotionChangeGoods.price) }}
						</view>
					</view>
				</view>
				<view class="promotion-box">
					<view class="title">
						选择促销
					</view>
					<u-radio-group v-model="promotionValue" wrap active-color="#d81e06">
						<u-radio 
							@change="promotionListChange" 
							v-for="(item, index) in promotionList" :key="index" 
							:name="item.id"
						>
							{{item.remark}}
						</u-radio>
					</u-radio-group>
				</view>
				<u-button type="error" @click="confirmChangePromotion">确定</u-button>
			</view>
		</u-popup>
		
		<vk-u-goods-sku-popup
			v-model="skuIsShow"
			border-radius="20"
			ref="vkUGoodsSkuPopup"
			:custom-action="findGoodsInfo"
			:mode="3"
			:defaultSelectNum="oldCartNum"
			:defaultSelectOptionId="oldCartOptionId"
			:closeImage="closeImage"
			:buyNowText="'确认'"
			@open="openSkuPopup"
			@close="closeSkuPopup"
			@buy-now="buyNow"
			goodsIdName="id"
			skuIdName="id"
			skuListName="options"
			specListName="specs"
			goodsThumbName="cover"
		></vk-u-goods-sku-popup>
		
	</view>
</template>

<script>
	import _ from '@holyhigh/func.js'
	import utils from '@/utils/index'
	import vkUGoodsSkuPopup from '@/plugins/vk-u-goods-sku-popup/vk-u-goods-sku-popup'
	export default{
		components:{
			vkUGoodsSkuPopup
		},
		computed:{
			selectOrderCount(){
				let count = 0;
				let total = 0;
				let totalGoodsMoney = 0
				this.cartList.map(item => {
					if(item.checked){
						count++
						total += item.paid
						totalGoodsMoney += item.price * item.total
					}
				})
				this.totalMoney = total
				this.totalGoodsMoney = totalGoodsMoney
				return count
			},
			isDisabled(){
				return this.selectOrderCount < 1 || this.isLoading
			},
			clacIsSelectAll(){
				return this.selectOrderCount == this.cartList.length
			},
			showPrice(){
				return this.cartFormatPrice(this.totalMoney);
			},
			// 总优惠金额
			totalDiscountPrice(){
				let total = 0;
				this.groupList.map(item => {
					if(item.activity_id > 0){
						total += item.discount_price
					}
				})
				
				return this.cartFormatPrice(total);
			}
		},
		onLoad() {
			
		},
		onShow() {
			if(this.$store.state.memberToken){
				this.getDataList()
			}
			else {
				this.isLogin = false
				uni.$emit('CART_COUNT_CHANGE',0)
			}
		},
		onHide() {
			this.changePromotionPopupShow = false
		},
		data() {
			return {
				closeImage:'/static/images/btn_sku_popup_close.png',
				skuIsShow: false,
				goodsId: 0,
				oldCartId: 0,
				oldCartNum: 0,
				oldCartOptionId: 0,
				
				couponDetails: false,
				utils:utils,
				saveLock:true, // 锁定保存
				cartList: [],
				photoBaseUrl: '',
				groupList: [],
				promotionList: [],
				promotionValue:0,
				promotionCartId:0,
				promotionChangeGoods: {
					goods_name: '',
					cover: '',
					price: 0
				},
				totalMoney:0,
				totalGoodsMoney:0,
				testNum:false,
				isSelectAll:false,
				changePromotionPopupShow:false,
				btnWidth: 130,
				isLoading: false,
				isLogin:true,
				options: [
					{
						text: '收藏',
						style: {
							backgroundColor: 'rgb(255, 198, 0)'
						}
					},
					{
						text: '删除',
						style: {
							backgroundColor: 'rgb(248, 36, 0)'
						}
					}
				],
				goodsInfo:{},
				activityNums: {}
			}
		},
		methods:{
			getDataList(){
				let that = this
				that.saveLock = true
				this.$api.cart.mycarts().then(res => {
					if (res.not_login){
						that.isLogin = false
						uni.$emit('CART_COUNT_CHANGE',0)
						return
					}
					that.photoBaseUrl = res.photo_base_url
					that.isLogin = true
					that.groupList = res.groups
					that.activityNums = res.activityNums
					// 加入左滑属性
					that.cartList = res.goodss.map(item => {
						item.show = false
						return item
					})
					that.calcIsSelectAll()
					// 加载数据成功后，延迟一点开启按钮操作
					setTimeout(() => {
						that.saveLock = false
					},500)
				})
				.catch(err => {
					if (err.code === 10003){
						that.isLogin = false
					}
				})
			},
			calcIsSelectAll(){
				const that = this
				uni.$emit('CART_COUNT_CHANGE',this.cartList.length)
				setTimeout(function(){
					// 延迟设置，列表长度为 0 不设置
					if (that.cartList.length < 1){
						return false
					}
					that.isSelectAll = (that.selectOrderCount == that.cartList.length)
				},100)
			},
			gotoGoodsDetails(_goodsId){
				utils.myUrl.gotoGoodsDetails(_goodsId)
			},
			changeGoodsOption(_row){
				const that = this
				that.goodsId = _row.goods_id;
				that.oldCartId = _row.id;
				that.oldCartNum = _row.total;
				uni.showLoading({
					
				})
				that.oldCartOptionId = _row.goods_option_id;
				that.$api.goods.details({id:_row.goods_id}).then(res => {
					that.goodsInfo = res
					that.goodsInfo.cover = that.photoBaseUrl + that.goodsInfo.cover
					
					that.skuIsShow = true
					
					uni.hideLoading()
				})
			},
			saveChangeCart(_item){
				uni.showLoading({
					
				})
				this.$api.cart.save({
					goods_id:_item['goods_id'],
					goods_option_id:_item['goods_option_id'],
					goods_num:_item['total'],
					is_selected:_item['checked'],
				}).then(res => {
					// 加入成功，刷新列表
					this.getDataList()
					uni.hideLoading()
				})
				.catch(err => {
					uni.hideLoading()
					// console.log(res)
					uni.showToast({
						title: err.message
					})
				})
			},
			cartFormatPrice(_price){
				return _.formatNumber((_price / 100),'0.00');
			},
			uNumberBoxChange(_data){
				const that = this
				that.cartList[_data['index']]['total'] = _data['value']
				// 锁定时不触发
				if (this.saveLock === false){
					that.$u.debounce(function(){
						
						that.saveChangeCart(that.cartList[_data['index']])
					},500)
				}
			},
			selectBtnClick(_item){
				_item.checked = !_item.checked
				this.saveChangeCart(_item)
			},
			checkboxChange(e) {
				let that = this
				that.calcIsSelectAll()
			},
			claerAllChecked(_checked){
				let that = this
				this.cartList.map(item => {
					item.checked = _checked
				})
				this.$api.cart.selected_all({'is_selected':_checked}).then(res => {
					that.$u.throttle(function(){
						that.getDataList()
					},500)
				})
			},
			selectAll(e){
				this.claerAllChecked(this.isSelectAll)
			},
			swipeActionOpen(index){
				let that = this
				that.cartList[index].show = true;
				that.cartList.map((val, idx) => {
					if(index != idx) that.cartList[idx].show = false;
				})
			},
			swipeActionClick(index,btnIndex){
				this.cartList[index].show = false;
				const model = this.cartList[index]
				this.cartList.splice(index, 1);
				if(btnIndex == 1) {
					this.$api.cart.del({id:model.id})
				} else {
					this.$api.goods.collection({id:model.goods_id,cart_id:model.id})
					this.$u.toast(`收藏成功`);
				}
				uni.$emit('CART_COUNT_CHANGE',this.cartList.length)
			},
			submitCart(){
				let that = this
				if(that.isDisabled){
					return
				}
				that.isLoading = true
				// 可以先检测，目前直接跳转
				setTimeout(function() {
					that.isLoading = false
				}, 3000);
				let submitData = []
				this.groupList.map((gg, idx) => {
					let tmp = {
						activity_id: gg.activity_id,
						coupon_ids: [0],
						cart_ids: []
					}
					this.cartList.map((cc, idx) => {
						if (cc.checked && gg.cart_ids.includes(cc.id)){
							tmp.cart_ids.push(cc.id)
						}
					})
					// 如果组里没有勾选的，则不加入该组
					if (tmp.cart_ids.length > 0){
						submitData.push(tmp)
					}
				})
				// 存放参数，防止太长 URL 不支持
				getApp().globalData.tmpSubmitData = { cart_data:submitData }
				// uni.setStorageSync('tmpSubmitData', { cart_data:submitData });
				this.$myRouter.push({name:'order/create', params: { cart_data:1 }})
			},
			showCouponDetails(){
				this.couponDetails = true;
			},
			listIsShow(goodsIds,goodsId){
				return goodsIds.includes(goodsId)
			},
			changePromotion(cartRow,activityId){
				uni.showLoading({})
				this.promotionCartId = cartRow.id
				this.$api.goods.details({id:cartRow.goods_id}).then(res => {
					console.log(res)
					uni.hideLoading()
					this.promotionChangeGoods.goods_name = res.goods_name
					this.promotionChangeGoods.cover = res.photo_base_url + res.cover
					this.promotionChangeGoods.price = cartRow.paid / cartRow.total
					
					this.promotionList = res.tags
					this.changePromotionPopupShow = true
					this.promotionValue = activityId
				})
			},
			isShowChangePromotion(cartId){
				let tmp = this.activityNums[cartId];
				if (!tmp){
					return false;
				}
				
				return tmp > 1;
			},
			promotionListChange(e){
				console.log(e)
			},
			confirmChangePromotion(){
				uni.showLoading({})
				this.$api.cart.confirmChangePromotion({id:this.promotionCartId,activity_id:this.promotionValue}).then(res => {
					console.log(res)
					uni.hideLoading()
					this.changePromotionPopupShow = false
					this.getDataList()
				}).catch(err => {
					console.log(err)
					uni.hideLoading()
				})
			},
			
			// 规格选择器
			openSkuPopup(){
				// console.log("监听 - 打开sku组件");
				this.$refs['vkUGoodsSkuPopup'].init()
			},
			closeSkuPopup(){
				// console.log("监听 - 关闭sku组件");
			},
			findGoodsInfo(e){
				const that = this
				return new Promise(function (resolve, reject) {
					resolve(that.goodsInfo);
				});
			},
			// 加入购物车前的判断
			addCartFn(obj){
				let { selectShop } = obj;
				let res = {};
				let name = selectShop.goods_name;
				if(selectShop.sku_name != "默认"){
					name += "-"+selectShop.sku_name;
				}
				res.msg = `${name} 已添加到购物车`;
				if(typeof obj.success == "function") obj.success(res);
			},
			// 立即购买 确定
			buyNow(selectShop){
				const that = this
				that.addCartFn({
					selectShop : selectShop,
					success : function(res){
						// 实际业务时,请替换自己的加入购物车逻辑
						that.$api.cart.change({
							goods_id:that.goodsId,
							cart_id:that.oldCartId,
							goods_num:selectShop.buy_num,
							goods_option_id:selectShop.id,
							is_selected:true,
						}).then(res => {
							that.skuIsShow = false
							that.saveLock = true
							that.getDataList()
							setTimeout(() => {
								that.saveLock = false
							},1500)
						}).catch(err => {
							uni.showToast({
								title: err.message,
								icon:"none"
							});
						})
					}
				});
			},
		},
	}
</script>

<style scoped lang="scss">
	.shopping-cart{
		.empty{
			margin-top: 300rpx;
		}
	}
	.cart-list{
		padding-bottom: 100px;
		.cart-item{
			min-height: 200rpx;
			background-color: #FFF;
			padding: 20rpx;
			display: flex;
			margin-bottom: 10px;

			.select-btn{
				display:flex;
				justify-content: center;
				align-items: center;
				text-align: center;
				
				&.is-disable{
					.txt{
						color: #d81e06;
						background-color: #CCC;
					}
				}
			}

			.goods-box{
				display: flex;


				.pictrue{
					width: 160rpx;
					height: 160rpx;
				}
				.goods-tips{
					margin-top: 10upx;
					font-size: 20upx;
					color: #d81e06;
				}
				.info{
					padding-left: 20rpx;
					.goods-name{
						display: -webkit-box;
						overflow:hidden;
						text-overflow: ellipsis;
						width: 62vw;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
					}
					.specs{
						margin-top: 5px;
						color: #747474;
						font-size: 24rpx;
						display: flex;
						justify-content: space-between;
						margin: 10rpx 0;
						
						.btn{
							padding: 4rpx 8rpx;
							background-color: #EEE;
							border-radius: 5px;
							
							.icon{
								margin-left: 4rpx;
								transform: scale(0.7,0.7);
							}
						}
					}
					.money{
						margin-top: 5px;
						display: flex;
						justify-content:space-between;

						.text{
							color: $gdbase-type-primary;
							font-size: 28rpx;
							font-weight: 700;
						}
					}
				}
			}
		}
	}
	.cart-item .goods-box .pictrue .img{
		width: 100%;
		height: 100%;
	}
	.cart-bar{
		display: flex;
		background-color: #FFF;
		border-top: 1px solid #CCC;
		min-height: 100rpx;
		position: fixed;
		width: 100vw;
		bottom: var(--window-bottom);
		justify-content:space-between;
		align-items:center;
		padding: 0 10px;
		z-index: 999;

		.money{
			width: 50vw;
			text-align: right;
			
			padding-right: 10px;
			.total{
				font-size: 32rpx;
			}
			.discount{
				color: $gdbase-type-primary;
				
				.discount-up{
					margin-left: 8rpx;
					/* #ifdef H5 */
					transform:scale(0.7,0.7)
					/* #endif */
				}
			}
		}
	}
	.addSite {
		display: flex;
		justify-content: space-around;
		width: 200rpx;
		line-height: 68rpx;
		background-color: $gdbase-type-primary;
		border-radius: 60rpx;
		font-size: 30rpx;
		.add{
			display: flex;
			align-items: center;
			color: #ffffff;
			.icon{
				margin-right: 10rpx;
			}
		}
		&.disabled{
			background-color: #CCC;
		}
	}
	.confirm-btn {
		width: 300px;
		height: 42px;
		line-height: 42px;
		border-radius: 30px;
		margin-top: 40rpx;
		background-color: #F00;
		color: #fff;
		font-size: 32rpx;
	
		&:after {
			border-radius: 60px;
		}
		
		&.disable{
			background-color: #CCC;
		}
	}
	.discount-price{
		color: #E41F19;
	}
	.cart-group{
		background-color: #FFF;
		margin-bottom: 20rpx;
		
		.cart-group-title{
			padding: 20rpx;
			border-bottom: 1px solid #EEE;
			
			.text{
				margin: 0 10rpx;
			}
		}
		.cart-group-remark{
			.promotion-text{
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				margin-left: 20rpx;
				font-size: 24rpx;
			}
		}
	}
	.promotion-popup-content{
		padding: 30rpx;
		.goods-box{
			display: flex;
			
			.info-right{
				font-size: 32rpx;
				margin-left: 30upx;
				
				.title{
					margin: 30rpx 0;
				}
				.price{
					font-weight: 700;
					color: #d81e06;
				}
			}
		}
		.goods-image{
			width: 180rpx;
		}
		.promotion-box{
			min-height: 600rpx;
			.title{
				font-weight: 700;
				margin: 20rpx 0;
			}
		}
	}
</style>
